package com.tanhua.manage.intercepter;

import com.tanhua.manage.pojo.User;
import com.tanhua.manage.service.UserService;
import com.tanhua.manage.utils.NoAuthorization;
import com.tanhua.manage.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author YuShiLong
 * @Date 2021/4/16 19:42
 * @Version 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断请求的方法是否包含@NoAuthorization,如果包含就不需要做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            //判断annotation
            if (annotation != null) {
                //结果不为null,放行
                return true;
            }
        }

        //获取token
        String token = request.getHeader("Authorization");
        //调用UserService里面的验证token方法，校验token是否有效
        User user = userService.queryUserByToken(token);
        //判断查询的结果
        if (null == user) {
            //没有查询到结果
            response.setStatus(401);//401:无权限
            return false;
        }

        //存储到当前的线程中
        UserThreadLocal.set(user);

        return true;
    }
}
